<template>
  <!-- 部门 -->
  <div class="innerPageTable-box-OneTwo positionInfo-page">
    <SelfAdaption>
      <Form
        :model="departmentForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 部门编码 -->
        <Form-item prop="code" :label="$t('module.orgManage.deptCode')">
          <Input
            type="text"
            
            v-model.trim="departmentForm.code"
            :maxlength="30"
            disabled
          ></Input>
        </Form-item>
        <!-- 部门名称 -->
        <Form-item prop="name" :label="$t('module.orgManage.deptName')">
          <Input
            type="text"
            
            v-model.trim="departmentForm.name"
            :maxlength="30"
            disabled
          ></Input>
        </Form-item>
      </Form>
    </SelfAdaption>

    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="formSearch"
        slot="adaption-bar"
        label-position="top"
        ref="companyInfoFormSearch"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 职位编码 -->
        <Form-item prop="companyCode" :label="$t('module.orgManage.jobCode')">
          <Input
            type="text"
            
            v-model.trim="formSearch.positionCode"
            :maxlength="30"
            :placeholder="$t('module.orgManage.enterJobCode')"
            @on-enter="search"
          ></Input>
        </Form-item>

        <!-- 职位名称 -->
        <Form-item prop="companyName" :label="$t('module.orgManage.jobName')">
          <Input
            type="text"
            
            v-model.trim="formSearch.positionName"
            :maxlength="30"
            :placeholder="$t('module.orgManage.enterJobName')"
            @on-enter="search"
          ></Input>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="formReset" />
        </Form-item>
      </Form>
    </SelfAdaption>

    <div class="single-table-con">
      <div class="table-bar">
        <RPButton optType="create" @click="addPosition('org', 'new')" />
        <!-- <CommonImportExport :configs="importExportConfigs"></CommonImportExport> -->
      </div>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100%;;"
        row-key="id"
        :border="false"
        lazy
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :row-class-name="rowClassName"
      >
        <el-table-column prop="code" :label="$t('module.orgManage.jobCode')" width="180"></el-table-column>
        <el-table-column prop="name" :label="$t('module.orgManage.jobName')" width="180"></el-table-column>
        <el-table-column prop="jobName" :label="$t('module.orgManage.position')"></el-table-column>
        <el-table-column prop="sort" :label="$t('module.orgManage.jobSort')" width="180"></el-table-column>
        <el-table-column :label="$t('module.orgManage.supervisorJobs')" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.mainPostFlag == 1 ? $t("module.orgManage.yes") : $t("module.orgManage.no") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.status')" width="120">
          <template slot-scope="scope">
            <StatusButton :status="scope.row.enabled == 1 ? '0' : '1'">
              {{
              scope.row.enabled == 1 ? $t("common.enable") : $t("common.disable")
              }}
            </StatusButton>
          </template>
        </el-table-column>
        <el-table-column :label="$t('module.orgManage.operation')" width="120">
          <template slot-scope="scope">
            <RowTools :data="RowToolsData(scope)" />
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 30px 0px 10px 10px;overflow: hidden">
        <div style="float: right;">
          <Page
            :total="page.total"
            :page-size-opts="[10, 20, 50, 100]"
            show-sizer
            show-total
            size="small"
            @on-change="changeCurrentPage"
            @on-page-size-change="changeCurrentSize"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getPositionInfo, getTableChildrenData } from "@/api/orgApi.js";
import { companyInfoColumns } from "../columns.js";
import locales from "../locales.js";

import newPosition from "./newPosition.vue";
import assignPosition from "./assignPosition.vue";
import CommonImportExport from '@/components/import-and-export/index.vue'

export default {
  name: "company-info",
  mixins: [locales],
  props: {
    departmentInfo: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  components: {
    CommonImportExport
  },
  data() {
    return {
      // 部门信息
      departmentForm: {
        name: "",
        code: ""
      },
      //
      positionInfo: {
        ascs: [],
        condition: {
          code: "",
          name: "",
          parentCode: "",
          tenantCode: ""
        },
        descs: [],
        pageNum: 1,
        pageSize: 10
      },
      page: {
        total: 0
      },
      // 搜索框的数据
      formSearch: {
        positionCode: "",
        positionName: ""
      },
      loading: false,
      tableHeight: window.innerHeight - 440,
      tableData: []
    };
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: getCompanyList,
        columnsFn: companyInfoColumns.bind(this)
      };
    },
    importExportConfigs() {
      const apiPrefix = window?.RPConfig?.mgt || ''
      return [
        {
          type: 'import',
          btnText: '导入',
          requestPath: `${apiPrefix}/position/importExcel`,
          successCallback: this.formReset
        },
        {
          type: 'export',
          btnText: '导出',
          requestPath: `${apiPrefix}/position/exportExcel`,
          requestMethod: 'post',
          requestParams: {
            code: this?.formSearch?.positionCode || '',
            name: this?.formSearch?.positionName || '',
            parentCode: this?.departmentInfo?.department?.orgCode || ''
          }
        },
        // 挂职和职位无拓展属性模板
        {
          type: 'export',
          btnText: '下载职位模板',
          requestPath: `${apiPrefix}/position/exportExcelMode`,
          requestMethod: 'post',
          requestParams: {}
        }
      ]
    }
  },
  created: function() {
    this.getDepartmentForm();
    this.getTableData();
  },
  mounted() {
    const that = this;
    window.onresize = () => {
      return (() => {
        window.tableHeight = window.innerHeight;
        that.tableHeight = window.tableHeight - 370;
      })();
    };
    this.search();
  },
  watch: {
    // // 这里的定时器是为了优化，如果频繁调用window.onresize方法会造成页面卡顿，增加定时器会避免频繁调用window.onresize方法
    // // timer默认值设置为false，这里相当于一个按钮，防止频繁改变时引起卡顿
    tableHeight(val) {
      if (!this.timer) {
        this.tableHeight = val;
        this.timer = true;
        const that = this;
        setTimeout(function() {
          that.timer = false;
        }, 400);
      }
    }
  },
  methods: {
    // 自定义行样式
    rowClassName(row) {
      //enabled:1-有效；0-无效
      let effectiveTime = this.$root.$options.filters["effective-time"](row.row.jobStartDate, row.row.jobEndDate);
      // 职位有效的情况下（无效情况下无需处理），所选职务无效为0 || 职务不在有效时间内为false，需灰化
      if (row.row.enabled == 1 && (row.row.jobEnabled == 0 || effectiveTime == false)) {
        return "tableDisableStyle";
      }
    },
    // 新建职位   idx:org部门下新建职位，dept代表新建子节点
    addPosition(idx, newOrEdit, row) {
      this.deptNodeData = row;
      new this.$pageModal(
        newPosition,
        {
          props: {
            propsPosintionInfo: {
              idx: idx,
              newOrEdit: newOrEdit,
              // 新建 如果在部门下新建职位（传部门编码）
              // 新建 如果新建子职位 （传父职位编码）
              parentCode: row == undefined ? this.departmentForm.code : row.code,
              row: newOrEdit == "edit" ? row : {},
              tenantCode: this.departmentInfo.tenantCode
            }
          }
        },
        data => {
          if (data) {
            if (data.newOrEdit == "new") {
              this.getTableData();
            } else if (data.newOrEdit == "edit") {
              this.getTableData();
            }
          }
        }
      );
    },
    // 部门信息
    getDepartmentForm() {
      this.departmentForm.code = this.departmentInfo.department.orgCode;
      this.departmentForm.name = this.departmentInfo.department.orgName;
    },
    // tree懒加载
    load(tree, treeNode, resolve) {
      this.getTableChildrenData(tree.code, resolve);
    },
    // 根据职位编码获取子节点数据
    getTableChildrenData(tree, resolve) {
      getTableChildrenData(tree, resolve).then(response => {
        let data = response.data;
        // resolve存在：代表是点击部门的树节点去加载子节点
        if (resolve) {
          if (data) {
            let arrData = data.map(item => {
              return {
                ...item,
                hasChildren: true
              };
            });
            resolve(arrData);
          } else {
            resolve([]);
          }
        }
      });
    },
    // 查询
    search() {
      this.positionInfo.condition.code = this.formSearch.positionCode;
      this.positionInfo.condition.name = this.formSearch.positionName;
      this.positionInfo.pageNum = 1;
      this.getTableData();
    },
    // 重置
    formReset() {
      this.formSearch.positionCode = "";
      this.formSearch.positionName = "";
      this.positionInfo.condition.code = "";
      this.positionInfo.condition.name = "";
      this.positionInfo.pageNum = 1;
      this.getTableData();
    },
    // 分页
    changeCurrentPage(page) {
      this.positionInfo.pageNum = page;
      this.getTableData();
    },
    changeCurrentSize(size) {
      this.positionInfo.pageSize = size;
      this.getTableData();
    },
    // 初始化列表数据
    getTableData() {
      this.tableData = [];
      this.positionInfo.condition.tenantCode = this.departmentInfo.tenantCode;
      this.positionInfo.condition.parentCode = this.departmentInfo.department.orgCode;
      getPositionInfo(this.positionInfo).then(response => {
        this.page.total = response.data.total;
        this.tableData = response.data.records.map(item => {
          return {
            ...item,
            hasChildren: true
          };
        });
      });
    },
    // 表格操作列的icon
    RowToolsData(scope) {
      return [
        {
          type: "icon",
          icon: "md-create",
          text: this.$t("module.orgManage.editPositon"),
          handle: () => {
            this.addPosition("edit", "edit", scope.row);
          }
        },
        {
          type: "icon",
          icon: "md-add",
          text: this.$t("module.orgManage.addPosition"),
          handle: () => {
            this.addPosition("dept", "new", scope.row);
          }
        },
        {
          type: "icon",
          icon: scope.row.enabled == 0 ? "" : "ios-person-add",
          text: this.$t("module.orgManage.assignAPost"),
          handle: () => {
            this.assignPosition("assign", "new", scope.row);
          }
        }
      ];
    },
    // 分配职位
    assignPosition(idx, newOrEdit, row) {
      new this.$sidelipPage(assignPosition, {
        props: {
          positionInfo: row,
          departmentForm: this.departmentForm,
          employeeInfo: {
            orgId: this.departmentInfo.department.orgId,
            positionCode: row.code,
            positionName: row.name
          }
        }
      });
    }
  }
};
</script>
<style lang="less">
.positionInfo-page {
  .title {
    margin-top: 15px;
  }
  .button-width {
    width: 38px;
    .ivu-icon-ios-undo {
      color: #666;
    }
    .ivu-icon-ios-undo:hover {
      color: #ff6f4b;
    }
  }
  .underLine {
    border-bottom: 1px solid #eeeeee;
  }
  .single-table-con {
    // height:calc(100%-410px) !important;
    // height:100%;
    .el-table {
      .el-table__header-wrapper {
        thead {
          color: #515a6e;
          tr {
            th {
              background: #f5f5f5 !important;
            }
          }
        }
      }
    }
    .table-bar .ivu-btn {
      margin-right: 8px;
    }
  }
}
</style>
